package cn.tedu._05weibo.base.exception;


import cn.tedu._05weibo.base.response.JsonResult;
import cn.tedu._05weibo.base.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult doHandlerIllegalArgumentException(IllegalArgumentException  e){
        String data=e.getMessage();
        log.error("IllegalArgumentException:"+data);
        return JsonResult.notok(data);
    }

//    @ExceptionHandler
//    public JsonResult doHandlerRuntimeException(RuntimeException  e){
//        String data=e.getMessage();
//        log.error("RuntimeException:"+data);
//        return JsonResult.notok();
//    }

    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        String data=e.getFieldError().getDefaultMessage();
        log.error("MethodArgumentNotValidException:"+data);
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }

    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException e){
        String[] datas=e.getMessage().split(":");
        String data=datas[1].trim();
        log.error("ConstraintViolationException:"+data);
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }


//    @ExceptionHandler
//    public JsonResult doHandlerThrowable(Throwable e){
//        String data=e.getMessage();
//        log.error("Throwable:"+data);
//        return new JsonResult(StatusCode.WEIZHI_EXCEPTION,data);
//    }
}
